package com.dudu.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dudu.mapper.ServicesMapper;
import com.dudu.pojo.Orders;
import com.dudu.pojo.Services;
import com.dudu.prop.WeiPayProperties;
import com.dudu.service.OrderService;
import com.dudu.service.ServicesService;
import com.dudu.service.WeiPayService;
import com.dudu.utils.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;

@Service
public class WeiPayServiceImpl implements WeiPayService {

    @Autowired
    private WeiPayProperties weiPayProperties;

    @Autowired
    private OrderService orderService;
    @Autowired
    private ServicesService servicesService;

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {

        Orders orderInfo = orderService.getById(orderId);
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        Map<String,String> map = new HashMap<String,String>();
        map.put("appid",weiPayProperties.getAppid());
        map.put("mch_id",weiPayProperties.getPartner());
        System.out.println(orderInfo.getOutTradeNo()+"sssssss");
        map.put("out_trade_no", orderInfo.getOutTradeNo());//商户订单号
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        try{
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, weiPayProperties.getPartnerkey()));
            httpClient.setHttps(true);
            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(content);
            System.out.println(stringStringMap);
            return stringStringMap; //支付

        } catch (Exception ex){
            return  null;
        }
    }

    @Override
    public String pay(Long orderId) {
        Orders orderInfo = orderService.getById(orderId);
        System.out.println(orderInfo+"----62");
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        Map<String,String> paramMap=new HashMap<String,String>();

        paramMap.put("appid",weiPayProperties.getAppid());
        paramMap.put("mch_id",weiPayProperties.getPartner());
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
//
//        Date reserveDate = orderInfo.getReserveDate();
//        String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
//        String body = reserveDateString + "就诊"+ orderInfo.getDepname();

        paramMap.put("body","商品test信息");
        System.out.println(orderInfo.getOutTradeNo()+"75");
        paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
        paramMap.put("total_fee","1");

        paramMap.put("spbill_create_ip","127.0.0.1");
        paramMap.put("notify_url","http://guli.shop/api/order/weixinPay/weixinNotify");
        paramMap.put("trade_type","NATIVE");



        try{
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, weiPayProperties.getPartnerkey()));//设置超参数
            httpClient.setHttps(true);//支持https协议
            httpClient.post(); //发送请求

            String xmlResult = httpClient.getContent();
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(xmlResult);

            return stringStringMap.get("code_url");
        }catch (Exception ex){
            return "";
        }

    }
//支付成功后的操作
    @Override
    public void paySuccess(Long orderId, Map<String, String> map) {
        //更新订单表的订单状态
        Orders orderInfo=new Orders();

        orderInfo.setOrderId(String.valueOf(orderId));

        orderInfo.setTransactionId(map.get("transaction_id"));

        orderService.updateById(orderInfo);
//        orderInfo.setStatus(1);
//        orderService.updateById(orderInfo);
        //更新服务表的支付状态
//        Services services=new Services();

        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        updateWrapper.set("pay_status",1);
        servicesService.update(updateWrapper);

    }

    public static String generateOrderNumber() {
        // 格式化当前时间（年月日时分秒毫秒）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStamp = sdf.format(new Date());

        // 生成一个随机数（这里简单使用4位随机数，你可以根据需要调整）
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数

        // 将时间戳和随机数拼接成订单号
        // 注意：这里简单拼接，实际项目中可能需要更复杂的逻辑来确保订单号的唯一性
        // 例如，如果系统并发量很高，仅使用时间戳+随机数可能无法保证唯一性
        // 你可能需要引入数据库的唯一索引、分布式ID生成器等机制
        return timeStamp + String.format("%04d", randomNum);
    }

    @Override
    public boolean saveBatch(Collection<Services> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<Services> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<Services> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Services entity) {
        return false;
    }

    @Override
    public Services getOne(Wrapper<Services> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Optional<Services> getOneOpt(Wrapper<Services> queryWrapper, boolean throwEx) {
        return Optional.empty();
    }

    @Override
    public Map<String, Object> getMap(Wrapper<Services> queryWrapper) {
        return Collections.emptyMap();
    }

    @Override
    public <V> V getObj(Wrapper<Services> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

    @Override
    public BaseMapper<Services> getBaseMapper() {
        return null;
    }

    @Override
    public Class<Services> getEntityClass() {
        return null;
    }
}
